<!--
 * @author: Goalias
 * @since: 2025-01-03
-->
<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import TextEditor from '@/components/TextEditor.vue'
import { DocumentAdd, RefreshRight, Delete } from '@element-plus/icons-vue'
import { postsApi } from '@/apis/PostsApi'
import { Posts } from '@/apis/types/Posts'
import PulsatingButton from '@/components/ui/pulsating-button'

const posts = ref<Posts[]>([])
const form = ref<Posts>({
    content: '',
})

const editorRef = ref<InstanceType<typeof TextEditor>>()
const formRef = ref<FormInstance>()

const rules = reactive<FormRules>({
    content: [
        { required: true, message: '请输入内容', trigger: 'blur' }
    ]
})

// 加载posts列表
const loadPosts = async () => {
    try {
        const res = await postsApi.getPosts(1, 10, null)
        posts.value = res.data
    } catch (error) {
        ElMessage.error('获取动态列表失败')
    }
}

onMounted(() => {
    loadPosts()
})

// 提交表单
const onSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    form.value.content = editorRef.value?.getHtml() || ''

    await formEl.validate(async (valid, fields) => {
        if (valid) {
            try {
                const response = await postsApi.addPosts(form.value)
                if (response.code === 200) {
                    ElMessage.success('发布成功！')
                    resetForm(formEl)
                    loadPosts() // 重新加载列表
                } else {
                    ElMessage.error('发布失败' + response?.msg)
                }
            } catch (error) {
                ElMessage.error('发布失败')
            }
        } else {
            ElMessage.error('发布内容验证失败，请检查输入！')
        }
    })
}

// 重置表单
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    if (editorRef.value) {
        editorRef.value.setHtml('')
    }
}

// 删除post
const handleDelete = async (id: number) => {
    try {
        const response = await postsApi.deletePosts(id)
        if (response.code === 200) {
            ElMessage.success('删除成功')
            loadPosts()
        } else {
            ElMessage.error('删除失败' + response?.msg)
        }
    } catch (error) {
        ElMessage.error('删除失败')
    }
}

// 切换置顶状态
const toggleTop = async (post: Posts) => {
    if (!post.id) return
    try {
        const updatedPost = { ...post, isTop: post.isTop === '1' ? '0' : '1' }
        const response = await postsApi.updatePosts(updatedPost)
        if (response.code === 200) {
            ElMessage.success('更新成功')
            loadPosts()
        } else {
            ElMessage.error('更新失败' + response?.msg)
        }
    } catch (error) {
        ElMessage.error('更新失败')
    }
}
</script>

<template>
    <div class="life-container">
        <!-- 创作区域 -->
        <div class="create-section">
            <h2 class="section-title">✨ 创建动态 ✨</h2>
            <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" class="post-form">
                <el-form-item label="动态内容" prop="content" class="editor-container">
                    <TextEditor ref="editorRef" :value="form.content" :category-id="-1" />
                </el-form-item>

                <el-form-item label="是否置顶" prop="isTop">
                    <el-switch v-model="form.isTop" active-value="1" inactive-value="0" active-text="是"
                        inactive-text="否" />
                </el-form-item>

                <el-form-item class="form-buttons">
                    <PulsatingButton type="button" pulseColor="var(--theme-color)" duration="2s" class="submit-button"
                        @click="onSubmit(formRef)">
                        <el-icon>
                            <DocumentAdd />
                        </el-icon>
                        发布动态
                    </PulsatingButton>
                    <PulsatingButton type="button" pulseColor="var(--theme-color)" duration="2s" class="submit-button"
                        @click="resetForm(formRef)">
                        <el-icon>
                            <RefreshRight />
                        </el-icon>
                        重置
                    </PulsatingButton>
                </el-form-item>
            </el-form>
        </div>

        <!-- 管理区域 -->
        <div class="manage-section">
            <h2 class="section-title">📝 动态管理 📝</h2>
            <div class="posts-list">
                <el-card v-for="post in posts" :key="post.id" class="post-card" shadow="hover">
                    <div class="post-header">
                        <span class="post-time">⏲️{{ post.createTime.replace('T', ' ').replace('Z', '') }}</span>
                        <div class="post-actions">
                            <el-tag :type="post.isTop === '1' ? 'success' : 'info'" class="top-tag"
                                @click="toggleTop(post)">
                                {{ post.isTop === '1' ? '已置顶' : '未置顶' }}
                            </el-tag>
                            <el-button type="danger" circle @click="handleDelete(post.id!)" class="delete-btn">
                                <el-icon>
                                    <Delete />
                                </el-icon>
                            </el-button>
                        </div>
                    </div>
                    <div class="post-content" v-html="post.content"></div>
                </el-card>
            </div>
        </div>
    </div>
</template>

<style scoped>
.life-container {
    min-height: 100vh;
    background-color: #f5f7fa;
    padding: 3vw;
}

.create-section,
.manage-section {
    background-color: #fff;
    padding: 3vw;
    border-radius: 2vw;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
    margin-bottom: 3vw;
    background: rgba(236, 222, 244, 0.816);
}

.section-title {
    margin-bottom: 3vh;
    color: #f2c05d;
    font-size: 1.8vw;
    text-align: center;
    font-weight: 600;
    background: linear-gradient(135deg, #409EFF 0%, #ff80f0 100%);
    border-radius: 1.5vw;
    padding: 1vw;
}

.post-form {
    max-width: 70vw;
    margin: 0 auto;
}

.editor-container {
    margin-bottom: 2vw;
}

.form-buttons {
    display: flex;
    justify-content: center;
    gap: 2vw;
}

.submit-button {
    display: flex;
    align-items: center;
    font-size: 1.2vw;
    margin-left: 10vw;
}

.posts-list {
    display: grid;
    gap: 1.5vw;
}

.post-card {
    transition: all 0.3s ease;
    background: #e6e4e4ef
}

.post-card:hover {
    transform: translateY(-5px);
}

.post-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1vw;
}

.post-time {
    color: #909399;
    font-size: 1.6vw;
}

.post-actions {
    display: flex;
    gap: 2vw;
    align-items: center;
    
}

.top-tag {
    cursor: pointer;
    transition: all 0.3s ease;
    font-size: 1.6vw;
}

.top-tag:hover {
    transform: scale(1.1);
}

.delete-btn {
    transition: all 0.3s ease;
    font-size: 1.6vw;
}

.delete-btn:hover {
    transform: scale(1.1);
    box-shadow: 0 0 10px rgba(255, 0, 0, 0.3);
}

.post-content {
    line-height: 1.6;
    color: #303133;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
}

:deep(.el-form-item__label) {
    background: linear-gradient(135deg, #409EFF 0%, #ff80f0 100%);
    border-radius: 1vw;
    margin-right: 1vw;
    color: #fff;
    padding: 0 1vw;
}
</style>